﻿using System.Text.RegularExpressions;
using NLog;

namespace TfsGiggle.Core
{
    /// <summary>
    /// Listens to notifications from TFS
    /// </summary>
    public sealed class CheckinService : ICheckinService
    {
        static Logger _logger = LogManager.GetCurrentClassLogger();
        readonly Regex changesetNumberRegex = new Regex(@"\<Number\>(?<changesetId>[\d]+)\</Number\>");
        readonly Regex teamProjectCollectionRegex = new Regex(@"pcguid=(?<guid>[0-9abcdef\\-]{36})");

        /// <summary>
        /// Called by TFS
        /// </summary>
        /// <param name="eventXml"></param>
        /// <param name="tfsIdentityXml"></param>
        public void Notify(string eventXml, string tfsIdentityXml)
        {
            _logger.Trace(eventXml);
            var changesetNumberMatch = changesetNumberRegex.Match(eventXml);
            if (changesetNumberMatch == null || changesetNumberMatch.Success == false)
            {
                _logger.Warn("Could not locate changesetid with the regular expression:{0}", changesetNumberRegex.ToString());
                return;
            }
            var teamProjectCollectionMatch = teamProjectCollectionRegex.Match(eventXml);
            if (teamProjectCollectionMatch == null || teamProjectCollectionMatch.Success == false)
            {
                _logger.Warn("Could not locate teamProjectCollectionId with the regular expression:{0}", teamProjectCollectionRegex.ToString());
                return;
            }
            int changesetId;
            var changeset = changesetNumberMatch.Groups["changesetId"].Value;
            if (int.TryParse(changeset, out changesetId))
            {
                var teamProjectCollectionId = teamProjectCollectionMatch.Groups["guid"].Value;
                _logger.Info("Adding job for teamProjectCollectionId:'{0}' ChangesetId:{1}", teamProjectCollectionId, changesetId);
                JobManager.Instance.AddJob(teamProjectCollectionId, changesetId);
            }
            else
            {
                _logger.Warn("Unable to parse changeset '{0}' to an int", changeset);
            }
            _logger.Trace("exit");
        }
    }
}
